package com.niuwa.p2p.service.job;

import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import javax.xml.bind.JAXB;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.niuwa.p2p.core.constant.YeePayModeEnum;
import com.niuwa.p2p.core.constant.YeePayServiceEnum;
import com.niuwa.p2p.core.constant.YeePaySubjoinEnum;
import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.core.utils.yeepay.WebUtil;
import com.niuwa.p2p.entity.yeepay.YeePayMongoInfo;
import com.niuwa.p2p.entity.yeepay.notify.AuthorizeAutoRepaymentNotity;
import com.niuwa.p2p.entity.yeepay.notify.AuthorizeAutoTransferNotity;
import com.niuwa.p2p.entity.yeepay.notify.BindBankCardNotity;
import com.niuwa.p2p.entity.yeepay.notify.CpTransactionNotity;
import com.niuwa.p2p.entity.yeepay.notify.RechargeNotify;
import com.niuwa.p2p.entity.yeepay.notify.RegisterNotify;
import com.niuwa.p2p.entity.yeepay.notify.WithdrawNotity;
import com.niuwa.p2p.entity.yeepay.supple.CpTransaction;
import com.niuwa.p2p.entity.yeepay.supple.RechargeRecord;
import com.niuwa.p2p.entity.yeepay.supple.SuppleAccountRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleAccountResponse;
import com.niuwa.p2p.entity.yeepay.supple.SuppleSingleQueryRequest;
import com.niuwa.p2p.entity.yeepay.supple.SuppleSingleQueryResponse;
import com.niuwa.p2p.entity.yeepay.supple.WithdrawRecord;
import com.niuwa.p2p.service.yeepay.YeePayMongoService;
import com.niuwa.p2p.service.yeepay.YeePayService;

/**
 * 
 * @title 易宝补单机制
 *
 * @author tennyqin
 * @version 1.0
 * @created 2015年4月10日
 */
@Component("yeePaySuppleJob")
public class YeePaySuppleJob {

//	@Autowired
	private YeePayMongoService yeePayMongoService;

	@Value("#{propertiesReader['yeepay.service.directUrl']}")
	private String directUrl;

	@Value("#{propertiesReader['yeepay.pfx.path']}")
	private String pfx;

	@Value("#{propertiesReader['yeepay.user.platformNo']}")
	private String platformNo;

	@Value("#{propertiesReader['yeepay.service.notifyUrl']}")
	private String notifyUrl;

	@Value("#{propertiesReader['yeepay.expire.mintutes']}")
	private Integer mintutes;

	private static Logger logger = Logger.getLogger(YeePaySuppleJob.class); // 日志记录

	@Autowired
	private YeePayService yeePayService;

	/**
	 * 易宝补单机制调度服务
	 */
	public void supplement() {

		List<YeePayMongoInfo> yeePayMongoInfos = yeePayMongoService.findAll();
		if (yeePayMongoInfos.size() > 0) {
			for (YeePayMongoInfo yeePayMongoInfo : yeePayMongoInfos) {
				if (timeIsOver(yeePayMongoInfo)) {// 超过了指定时间
					// 根据不同的查询类型进行不同的封装
					if (yeePayMongoInfo.getYeePaySubjoinEnum().toString()
							.equals(YeePaySubjoinEnum.ACCOUNT_INFO.toString())) {
						SuppleAccountRequest request = new SuppleAccountRequest();
						request.setPlatformNo(yeePayMongoInfo
								.getPlatformUserNo());
						request.setPlatformNo(platformNo);
						// 获取查询结果
						SuppleAccountResponse suppleAccountResponse = yeePayService
								.doAccoutInfo(request);
						if (null != suppleAccountResponse) {
							if (null == yeePayMongoInfo.getYeePayServiceEnum()) {
								return;
							}
							// 账号查询对应回调机制[个人注册、企业注册、绑卡、自动投标授权]
							doCallAccountNotify(yeePayMongoInfo,
									suppleAccountResponse);
						} else {
							// 移除掉mongdb的key
							delMongoKey(yeePayMongoInfo);
						}
					}
					if (yeePayMongoInfo.getYeePaySubjoinEnum().toString()
							.equals(YeePaySubjoinEnum.QUERY.toString())) {
						SuppleSingleQueryRequest request = new SuppleSingleQueryRequest();
						request.setPlatformNo(platformNo);
						request.setRequestNo(String.valueOf(yeePayMongoInfo
								.getRequestNo()));
						if (yeePayMongoInfo.getYeePayServiceEnum().equals(
								YeePayServiceEnum.RECHARGE)) { // 充值记录
							request.setMode(YeePayModeEnum.RECHARGE_RECORD);
						}
						if (yeePayMongoInfo.getYeePayServiceEnum().equals(
								YeePayServiceEnum.WITHDRAW)) { // 提现记录
							request.setMode(YeePayModeEnum.WITHDRAW_RECORD);
						}
						if (yeePayMongoInfo.getYeePayServiceEnum().equals(
								YeePayServiceEnum.TRANSACTION)
								|| yeePayMongoInfo
										.getYeePayServiceEnum()
										.equals(YeePayServiceEnum.AUTHORIZE_AUTO_REPAYMENT)) { // 划款记录
							request.setMode(YeePayModeEnum.CP_TRANSACTION);
						}
						// 获取查询结果
						SuppleSingleQueryResponse suppleSingleQueryResponse = yeePayService
								.doSingleQuery(request);
						if (null == suppleSingleQueryResponse) {
							// 移除掉mongdb的key
							delMongoKey(yeePayMongoInfo);
							return;
						}
						doCallTransactionNotify(yeePayMongoInfo,
								suppleSingleQueryResponse);
					}
				}
			}
		}
	}

	// 验证当前对象的时间是否超过了设置的时间
	private Boolean timeIsOver(YeePayMongoInfo yeePayMongoInfo) {
		Integer orginTime = mintutes + 480; //[补时差] mongDB里面数据少8*60分钟=8个小时
		Date realTime = DateUtil.addMinutes(yeePayMongoInfo.getCreateDate(),
				orginTime);
		if (DateUtil.isBefore(realTime, new Date())) { // 超过了指定时间
			return true;
		} else {
			return false;
		}
	}

	// 账户查询部分
	private void doCallAccountNotify(YeePayMongoInfo yeePayMongoInfo,
			SuppleAccountResponse response) {
		// 已经激活则需要回调webservice
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.REGISTER)) {
			RegisterNotify registerNotify = new RegisterNotify();
			registerNotify
					.setBizType(yeePayMongoInfo.getYeePayServiceEnum().REGISTER
							.toString());
			registerNotify.setCode(response.getCode());
			registerNotify.setPlatformNo(platformNo);
			registerNotify.setPlatformUserNo(yeePayMongoInfo
					.getPlatformUserNo());
			registerNotify.setMessage("执行注册补单操作服务");
			registerNotify.setRequestNo(String.valueOf(yeePayMongoInfo
					.getRequestNo()));
			doCallNotify(registerNotify, yeePayMongoInfo);
		}
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.BIND_BANK_CARD)) {
			BindBankCardNotity bindBankCardNotity = new BindBankCardNotity();
			bindBankCardNotity.setBizType(yeePayMongoInfo
					.getYeePayServiceEnum().BIND_BANK_CARD.toString());
			bindBankCardNotity.setMessage("执行绑卡补单操作服务");
			bindBankCardNotity.setPlatformNo(platformNo);
			bindBankCardNotity.setCode(response.getCode());
			bindBankCardNotity.setRequestNo(String.valueOf(yeePayMongoInfo
					.getRequestNo()));
			bindBankCardNotity.setPlatformUserNo(yeePayMongoInfo
					.getPlatformUserNo());
			bindBankCardNotity.setBank(response.getBank());
			bindBankCardNotity.setCardNo(response.getCardNo());
			bindBankCardNotity.setCardStatus(response.getCardStatus());
			doCallNotify(bindBankCardNotity, yeePayMongoInfo);
		}
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.AUTHORIZE_AUTO_TRANSFER)) {
			AuthorizeAutoTransferNotity authorizeAutoTransferNotity = new AuthorizeAutoTransferNotity();
			authorizeAutoTransferNotity.setBizType(yeePayMongoInfo
					.getYeePayServiceEnum().AUTHORIZE_AUTO_TRANSFER.toString());
			authorizeAutoTransferNotity.setPlatformNo(platformNo);
			authorizeAutoTransferNotity.setPlatformUserNo(yeePayMongoInfo
					.getPlatformUserNo());
			if (response.getAutoTender().equals("true")) {
				authorizeAutoTransferNotity.setCode("1");
			} else {
				authorizeAutoTransferNotity.setCode("0");
			}
			authorizeAutoTransferNotity.setMessage("执行自动投标授权补单操作服务");
			doCallNotify(authorizeAutoTransferNotity, yeePayMongoInfo);
		}

	}

	// 单笔查询部分
	private void doCallTransactionNotify(YeePayMongoInfo yeePayMongoInfo,
			SuppleSingleQueryResponse response) {
		// 充值记录
		List<RechargeRecord> rechargeRecords = response
				.getRechargeRecordResponse().getRecords().getRecords();
		// 提现记录
		List<WithdrawRecord> withdrawRecords = response
				.getWithdrawRecordResponse().getRecords().getRecords();
		// 划款记录
		List<CpTransaction> cpTransactionRecords = response
				.getCpTransactionResponse().getRecords().getRecords();
		RechargeRecord rechargeRecord = null;
		WithdrawRecord withdrawRecord = null;
		CpTransaction cpTransaction = null;
		if (rechargeRecords.size() > 0) {
			rechargeRecord = rechargeRecords.get(0);
		}
		if (withdrawRecords.size() > 0) {
			withdrawRecord = withdrawRecords.get(0);
		}
		if (cpTransactionRecords.size() > 0) {
			cpTransaction = cpTransactionRecords.get(0);
		}
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.RECHARGE)) {
			if (null == rechargeRecord || null == rechargeRecord.getAmount()) {
				// 移除掉mongdb的key
				delMongoKey(yeePayMongoInfo);
				return;
			} else {
				RechargeNotify rechargeNotify = new RechargeNotify();
				rechargeNotify.setBizType(yeePayMongoInfo
						.getYeePayServiceEnum().RECHARGE.toString());
				rechargeNotify.setMessage("执行充值补单操作服务");
				rechargeNotify.setPlatformNo(platformNo);
				if (response.getRechargeRecordResponse().getRecords().getRecords().get(0)
						.getStatus().equals("SUCCESS")) {
					rechargeNotify.setCode("1");
				} else {
					rechargeNotify.setCode("0");
				}
				rechargeNotify.setRequestNo(String.valueOf(yeePayMongoInfo
						.getRequestNo()));
				rechargeNotify.setPlatformUserNo(yeePayMongoInfo
						.getPlatformUserNo());
				rechargeNotify.setAmount(response.getRechargeRecordResponse()
						.getRecords().getRecords().get(0).getAmount());
				// rechargeNotify.setFeeMode(feeMode); [手续费和费率无法进行比对]
				doCallNotify(rechargeNotify, yeePayMongoInfo);
			}
		}
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.WITHDRAW)) {
			if (null == withdrawRecord || null == withdrawRecord.getAmount()) {
				// 移除掉mongdb的key
				delMongoKey(yeePayMongoInfo);
				return;
			} else {
				WithdrawNotity withdrawNotity = new WithdrawNotity();
				withdrawNotity.setBizType(yeePayMongoInfo
						.getYeePayServiceEnum().WITHDRAW.toString());
				withdrawNotity.setMessage("执行提现补单操作服务");
				withdrawNotity.setPlatformNo(platformNo);
				if (response.getWithdrawRecordResponse().getRecords().getRecords().get(0)
						.getStatus().equals("SUCCESS")) {
					withdrawNotity.setCode("1");
				} else {
					withdrawNotity.setCode("0");
				}
				withdrawNotity.setRequestNo(String.valueOf(yeePayMongoInfo
						.getRequestNo()));
				withdrawNotity.setPlatformUserNo(yeePayMongoInfo
						.getPlatformUserNo());
				withdrawNotity.setAmount(response.getWithdrawRecordResponse()
						.getRecords().getRecords().get(0).getAmount());
				// fee 手续费用 feeMode【见费率模式】withdrawType【见提现模式】 bank[银行代码]
				// cardNo[银行卡][单笔查询接口无法核对]
				doCallNotify(withdrawNotity, yeePayMongoInfo);
			}
		}
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.AUTHORIZE_AUTO_REPAYMENT)) {
			if (null == cpTransaction || null == cpTransaction.getStatus()) {
				// 移除掉mongdb的key
				delMongoKey(yeePayMongoInfo);
				return;
			} else {
				AuthorizeAutoRepaymentNotity authorizeAutoRepaymentNotity = new AuthorizeAutoRepaymentNotity();
				authorizeAutoRepaymentNotity.setBizType(yeePayMongoInfo
						.getYeePayServiceEnum().AUTHORIZE_AUTO_REPAYMENT
						.toString());
				authorizeAutoRepaymentNotity.setMessage("执行自动还款授权补单操作服务");
				authorizeAutoRepaymentNotity.setPlatformNo(platformNo);
				if (response.getCpTransactionResponse().getRecords().getRecords().get(0)
						.getStatus().equals("PREAUTH")) { // 已授权
					authorizeAutoRepaymentNotity.setCode("1");
				} else {
					authorizeAutoRepaymentNotity.setCode("0");
				}
				authorizeAutoRepaymentNotity.setPlatformUserNo(yeePayMongoInfo
						.getPlatformUserNo());
				// orderNo 标的号无法封装
				doCallNotify(authorizeAutoRepaymentNotity, yeePayMongoInfo);
			}
		}
		if (yeePayMongoInfo.getYeePayServiceEnum().equals(
				YeePayServiceEnum.TRANSACTION)) {
			if (null == cpTransaction || null == cpTransaction.getStatus()) {
				// 移除掉mongdb的key
				delMongoKey(yeePayMongoInfo);
				return;
			} else {
				CpTransactionNotity cpTransactionNotity = new CpTransactionNotity();
				cpTransactionNotity.setBizType(yeePayMongoInfo
						.getYeePayServiceEnum().TRANSACTION.toString());
				cpTransactionNotity.setMessage("执行转账授权补单操作服务");
				cpTransactionNotity.setPlatformNo(platformNo);
				cpTransactionNotity.setCode(response.getCpTransactionResponse()
						.getCode());
				cpTransactionNotity.setRequestNo(String.valueOf(yeePayMongoInfo
						.getRequestNo()));
				cpTransactionNotity.setStatus(response
						.getCpTransactionResponse().getRecords().getRecords().get(0)
						.getStatus());
				doCallNotify(cpTransactionNotity, yeePayMongoInfo);
			}
		}

	}

	private void doCallNotify(Object obj, YeePayMongoInfo yeePayMongoInfo) {
		StringWriter w = new StringWriter();
		JAXB.marshal(obj, w);
		String s = w.toString();
		s = s.replaceAll("[\\r\\n]", "");
		// 调用webservice
		StringBuffer params = new StringBuffer();
		params.append("notify=" + s);
		params.append("&sign=" + yeePayMongoInfo.getSign());
		try {
			String callValue = WebUtil.sendPost(notifyUrl, params.toString());
			// 三次重试
			for (int i = 0; i < 3; i++) {
				if (!"SUCCESS".equals(callValue)) {
					callValue = WebUtil.sendPost(notifyUrl, params.toString());
					Thread.sleep(1000 * 3); // 等待3秒
				}
			}
		} catch (Exception ex) {
			logger.error("执行回调webservice补单操作失败!!", ex);
			ex.printStackTrace();
		}
	}

	// 删除掉mongoDb队列
	private void delMongoKey(YeePayMongoInfo notifyResponse) {
		String requestNo = notifyResponse.getRequestNo();
		String platformUserNo = notifyResponse.getPlatformUserNo();
		if (null != requestNo) {
			yeePayMongoService.delete(requestNo);
		} else {
			// 自动投标授权和自动还款授权比较特殊
			if (notifyResponse.getYeePayServiceEnum() == YeePayServiceEnum.AUTHORIZE_AUTO_TRANSFER
					|| notifyResponse.getYeePayServiceEnum() == YeePayServiceEnum.AUTHORIZE_AUTO_REPAYMENT) {
				if (null != platformUserNo) {
					yeePayMongoService.deleteByUserNo(platformUserNo);
				}
			}

		}
	}
}
